﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WGM_Client_Net35V2.HelperClasses;
using WGM_Client_Net35V2.Properties;

namespace WGM_Client_Net35V2.Views
{
    /// <summary>
    /// Interaction logic for LoginView.xaml
    /// </summary>
    public partial class LoginView : UserControl
    {
        MainWindow _mainWindow;
        public string Username { get { return _usernameTB.Text; } private set { _usernameTB.Text = value; } }
        public string Password { get { return _passwordTB.Password; } private set { _passwordTB.Password = value; } }
        public LoginView()
        {
            ClassRegistry.AddClass(this);
            InitializeComponent();
            
            _mainWindow = ClassRegistry.GetClass(typeof(MainWindow)) as MainWindow;
            _mainWindow.WGMClient.LogInCompleted += new EventHandler<WGM_Client_Net35V2.WGM_Svc.LogInCompletedEventArgs>(WGMClient_LogInCompleted);
            if (Settings.Default.RememberLogin == true)
            {
                _rememberLoginChk.IsChecked = true;
                Username = Settings.Default.LastLoginName;
                Password = Settings.Default.LastLoginPassword;
            }
        }

        void WGMClient_LogInCompleted(object sender, WGM_Client_Net35V2.WGM_Svc.LogInCompletedEventArgs e)
        {
            _mainWindow.ClearAlert();
            this.IsEnabled = true;
            if (e.Error == null)
            {
                if (e.Result == true)
                {
                    _mainWindow.MainTab.IsSelected = true;
                    _mainWindow.RetrievePlaces();
                }
                else
                {
                    _mainWindow.ShowAlert(Colors.DarkSlateGray, e.message);
                }
            }
            else
            {
                _mainWindow.ShowAlert(Colors.Red,"Error Contacting Server...");
            }
        }

        private void OnLoginClick(object sender, MouseButtonEventArgs e)
        {
            Settings.Default.RememberLogin = _rememberLoginChk.IsChecked.Value;
            if (_rememberLoginChk.IsChecked.Value == true)
            {
                Settings.Default.LastLoginName = _usernameTB.Text;
                Settings.Default.LastLoginPassword = _passwordTB.Password;
            }
            Settings.Default.Save();
            _mainWindow.WGMClient.LogInAsync(Username, Password,Settings.Default.LastMacAddress );
            this.IsEnabled = false;
            _mainWindow.ShowAlert(Colors.Black,"Loging in...");
        }


    }
}
